package com.zygh.lz.component;

import com.zygh.lz.dao.OperationMapper;
import com.zygh.lz.entity.Operation;
import com.zygh.lz.service.OperationService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

/**
 * 异步上传日志
 */
@Component
public class MyStartupRunner implements CommandLineRunner {

    @Resource
    private OperationService operationService;
    @Resource
    private OperationMapper operationMapper;


    private final static Logger logger = LoggerFactory.getLogger(MyStartupRunner.class);

    @Override
    public void run(String... args) {
        new Thread() {
            @Override
            public void run() {
                try {
                    logger.info(">>>>>>>>>>>>>>>服务启动执行，执行加载数据等操作<<<<<<<<<<<<<");
                    myrun();
                } catch (Exception e) {
                    logger.error(">>>>>>>>>" + e.toString());
                }
            }
        }.start();
    }


    private void myrun() {
        List<Operation> allOperationByState = operationMapper.findAllOperationByState();
        if (allOperationByState.size() > 0) {
            logger.info(">>>>>>>>>>>>>>>开始上传<<<<<<<<<<<<<<<<<<");
            try {
                operationService.uploadLog();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }


    }


    /**
     * 每半个小时上传一次日志
     *
     * @throws IOException
     */
    @Scheduled(cron = "0 0/30 * * * ?")
    public void UploadLog() throws Exception {
        List<Operation> allOperationByState = operationMapper.findAllOperationByState();
        if (allOperationByState.size() > 0) {
            operationService.uploadLog();

        }

    }

    /**
     * 每二十分钟监测日志有没有空警号的，如果有删除，影响上传
     *
     * @throws IOException
     */
    @Scheduled(cron = "0 0/20 * * * ?")
    public void monitor() {
        List<Operation> allOperationByState = operationMapper.findAllOperationByState();
        allOperationByState.forEach(operation -> {
            if (StringUtils.isEmpty(operation.getPoliceId())) {
                operationMapper.deleteByPrimaryKey(operation.getId());
            }
        });

    }


}